package com.baoyouqun.API.gps;

import com.alibaba.cola.dto.Response;
import com.alibaba.cola.dto.SingleResponse;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

@Service
public class LocationService {

    private final ObjectMapper objectMapper = new ObjectMapper();
    @Resource
    private AmapConfig amapConfig;
    @Resource
    private RestTemplate restTemplate;

    /**
     * 根据经纬度获取城市信息（调用高德地图API）
     */
    public SingleResponse<JsonNode> getCityByLocation(Double longitude, Double latitude) throws IOException {
        String url = String.format(
                "https://restapi.amap.com/v3/geocode/regeo?location=%s,%s&key=%s",
                longitude, latitude, amapConfig.getAmapKey()
        );

        HttpHeaders headers = new HttpHeaders();
        HttpEntity<String> entity = new HttpEntity<>(headers);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);

        JsonNode rootNode = objectMapper.readTree(response.getBody());
        if (!"1".equals(rootNode.get("status").asText())) {
            Response.buildFailure("100401", "获取地理位置信息失败: " + rootNode.get("info").asText());
        }

        JsonNode addressComponent = rootNode.get("regeocode").get("addressComponent");
        return SingleResponse.of(addressComponent);
    }
}